<template>
  <canvas ref="container" class="w-full h-full"></canvas>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { WebGL } from "../../lib/webgl/WebGL";
import {
  getModelViewMatrix,
  getProjectionMatrix,
} from "../../lib/math/GetMatrix";

const container = ref(null);
const webgl = new WebGL();
let oldTime = Date.now();

const cube = {
  vertex: new Float32Array([
    // float3 position, float3 normal
    // face1
    1, 1, 1, 1, 0, 0, 1, 1, -1, 1, 0, 0, 1, -1, 1, 1, 0, 0, 1, -1, -1, 1, 0, 0,
    // face2
    -1, 1, -1, -1, 0, 0, -1, 1, 1, -1, 0, 0, -1, -1, -1, -1, 0, 0, -1, -1, 1,
    -1, 0, 0,
    // face3
    -1, 1, -1, 0, 1, 0, 1, 1, -1, 0, 1, 0, -1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0,
    // face4
    -1, -1, 1, 0, -1, 0, 1, -1, 1, 0, -1, 0, -1, -1, -1, 0, -1, 0, 1, -1, -1, 0,
    -1, 0,
    // face5
    -1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, -1, -1, 1, 0, 0, 1, 1, -1, 1, 0, 0, 1,
    // face6
    1, 1, -1, 0, 0, -1, -1, 1, -1, 0, 0, -1, 1, -1, -1, 0, 0, -1, -1, -1, -1, 0,
    0, -1,
  ]),
  index: new Uint8Array([
    0, 2, 1, 2, 3, 1, 4, 6, 5, 6, 7, 5, 8, 10, 9, 10, 11, 9, 12, 14, 13, 14, 15,
    13, 16, 18, 17, 18, 19, 17, 20, 22, 21, 22, 23, 21,
  ]),
  vertexCount: 24,
  indexCount: 36,
};

function initShader(gl) {
  let vertexShader = gl.createShader(gl.VERTEX_SHADER);
  gl.shaderSource(
    vertexShader,
    `
      attribute vec3 a_Position;
      attribute vec3 a_Normal;
      varying vec3 v_Position;
      varying vec3 v_Normal;
      uniform mat4 u_ModelViewMatrix;
      uniform mat4 u_ProjectionMatrix;
      void main() {
        mat4 mvpMatrix = u_ProjectionMatrix * u_ModelViewMatrix;
        vec4 pos = vec4(a_Position, 1.0);
        vec4 nor = vec4(a_Normal, 0.0);
  
        gl_Position = mvpMatrix * vec4(a_Position, 1.0);
        v_Position = (u_ModelViewMatrix * pos).xyz;
        v_Normal = (u_ModelViewMatrix * nor).xyz;
      }
      `
  );
  gl.compileShader(vertexShader);

  let fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  gl.shaderSource(
    fragmentShader,
    `
      precision mediump float;
      varying vec3 v_Position;
      varying vec3 v_Normal;
      uniform float u_AmbientLight;
      uniform float u_DirectionLight[8];
      uniform float u_PointLight[8];
      void main() {
        vec3 color = vec3(1.0, 0.0, 0.0);
        vec3 result = color * u_AmbientLight;
  
        vec3 directionPosition = vec3(u_DirectionLight[0], u_DirectionLight[1], u_DirectionLight[2]);
        float directionIntensity = u_DirectionLight[4];
        float directionDiffuse = max(dot(normalize(directionPosition), v_Normal), 0.0);
        result += color * directionIntensity * directionDiffuse;
  
        vec3 pointPosition = vec3(u_PointLight[0], u_PointLight[1], u_PointLight[2]);
        float pointIntensity = u_PointLight[4];
        float pointRadius = u_PointLight[5];
        vec3 pointDir = pointPosition - v_Position;
        float distance = length(pointDir);
        if(distance < pointRadius){
            float pointDiffuse = max(dot(normalize(pointDir), v_Normal), 0.0);
            float distanceFactor = pow(1.0 - distance / pointRadius, 2.0);
            result += color * pointIntensity * pointDiffuse * distanceFactor;
        }
  
        gl_FragColor = vec4(result, 1.0);
      }
      `
  );
  gl.compileShader(fragmentShader);

  let program = gl.createProgram();
  gl.attachShader(program, vertexShader);
  gl.attachShader(program, fragmentShader);
  gl.linkProgram(program);

  gl.useProgram(program);
  gl.program = program;

  gl.enable(gl.DEPTH_TEST);
}

function draw(gl) {
  let vertexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, cube.vertex, gl.STATIC_DRAW);

  let a_Position = gl.getAttribLocation(gl.program, "a_Position");
  gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, 6 * 4, 0);
  gl.enableVertexAttribArray(a_Position);

  let a_Normal = gl.getAttribLocation(gl.program, "a_Normal");
  gl.vertexAttribPointer(a_Normal, 3, gl.FLOAT, false, 6 * 4, 3 * 4);
  gl.enableVertexAttribArray(a_Normal);

  let indexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, cube.index, gl.STATIC_DRAW);
}

function tick(gl, modelViewMatrix, projectionMatrix) {
  let u_ModeoViewMatrix = gl.getUniformLocation(
    gl.program,
    "u_ModelViewMatrix"
  );
  gl.uniformMatrix4fv(u_ModeoViewMatrix, false, modelViewMatrix);

  let u_ProjectionMatrix = gl.getUniformLocation(
    gl.program,
    "u_ProjectionMatrix"
  );
  gl.uniformMatrix4fv(u_ProjectionMatrix, false, projectionMatrix);

  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);

  gl.drawElements(gl.TRIANGLES, cube.indexCount, gl.UNSIGNED_BYTE, 0);
}

function init() {
  let canvas = container.value;
  let gl = webgl.initWebGL(canvas);
  initShader(gl);

  let aspect = canvas.width / canvas.height;
  let position = { x: 0, y: 0, z: -5 };
  let rotation = { x: 0.5, y: 0, z: 0 };
  let scale = { x: 1, y: 1, z: 1 };
  draw(gl);

  let ambient = 0.1;
  let u_AmbientLight = gl.getUniformLocation(gl.program, "u_AmbientLight");
  gl.uniform1f(u_AmbientLight, ambient);
  let direction = new Float32Array([1, 0, 1, 1, 0.5, 0, 0, 0]);
  let u_DirectionLight = gl.getUniformLocation(gl.program, "u_DirectionLight");
  gl.uniform1fv(u_DirectionLight, direction);
  let point = new Float32Array([-5, 0, -5, 1, 1, 20, 0, 0]);
  let u_PointLight = gl.getUniformLocation(gl.program, "u_PointLight");
  gl.uniform1fv(u_PointLight, point);

  function frame() {
    let newTime = Date.now();
    let delta = (newTime - oldTime) / 1000;
    oldTime = newTime;

    rotation.y -= delta * 1;
    let modelViewMatrix = getModelViewMatrix(position, rotation, scale);
    let projectionMatrix = getProjectionMatrix(aspect);
    tick(gl, modelViewMatrix, projectionMatrix);

    requestAnimationFrame(frame);
  }
  frame();

  window.addEventListener("resize", () => {
    canvas.width = canvas.clientWidth;
    canvas.height = canvas.clientHeight;
    aspect = canvas.width / canvas.height;
    gl.viewport(0, 0, canvas.width, canvas.height);
  });
}

onMounted(() => {
  init();
});
</script>
